package pl.diagnoser.server.persistance.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import pl.diagnoser.client.dto.AppDTO;
import pl.diagnoser.server.persistance.map.App;
import pl.diagnoser.server.persistance.tools.HibernateUtil;

public class AppDao implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@SuppressWarnings("unchecked")
	public App getActiveApp() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		
		List<App> app = session.createCriteria(App.class).add(Restrictions.eq("isActive", 1)).list();
		if(app.size() > 1)
			app = null;
		session.getTransaction().commit();
		session.close();
		if(app != null)
			return app.get(0);
		else
			return null;
	}
	
	@SuppressWarnings("unchecked")
	public List<AppDTO> getAllApp() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		
		List<App> appList = new ArrayList<App>(session.createQuery("from App").list());
		List<AppDTO> appDTO = new ArrayList<AppDTO>(appList != null ? appList.size() : 0);
		if(appList != null) {
			for (App app : appList) {
				appDTO.add(createAppDTO(app));
			}
		}
		
		session.getTransaction().commit();
		session.close();
		return appDTO;
	}
	
	public String updateApp(Long appID, int isActive, String appName, int isSearchMode) {
		String ok = "OK";
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		
		App app = null;
		
		if(appID != null) {
			app = (App)session.createCriteria(App.class).add(Restrictions.eq("appId", appID)).uniqueResult();
			app.setIsActive(isActive);
			app.setIsSearchMode(isSearchMode);
			session.update(app);
		} else {
			app = new App(null, appName, isActive, isSearchMode);
			session.save(app);
		}
		
		session.getTransaction().commit();
		session.close();
		
		return ok;
	}
	
	public String removeApp(String appName) {
		String ok = "OK";
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		
		if(appName != null) {
			App app = (App)session.createCriteria(App.class).add(Restrictions.eq("appName", appName)).uniqueResult();
			session.delete(app);
		}
		
		session.getTransaction().commit();
		session.close();
		
		return ok;
	}
	
	public AppDTO createAppDTO(App app) {
		return new AppDTO(app.getAppId(), app.getAppName(), app.getIsActive(), app.getIsSearchMode());
	}
}
